package com.weibei.web.util.file;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.UrlSafeBase64;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件上传工具类
 * 
 * @author ruoyi
 */
@Slf4j
@Component
public class FileUploadUtil
{
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认文件类型jpg
     */
    public static final String IMAGE_JPG_EXTENSION = ".jpg";

    private static int counter = 0;

    // 设置需要操作的账号的AK和SK
    @Value("${qiniu.accessKey}")
    private String ACCESS_KEY;
    @Value("${qiniu.secretKey}")
    private String SECRET_KEY;

    // 要上传的空间名称
    @Value("${qiniu.bucketname}")
    private String BUCKETNAME;

    // 密钥
//    private Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    // 外链默认域名
    @Value("${qiniu.domain}")
    private String DOMAIN;

    //配置类
    private static Configuration cfg = new Configuration(Zone.zone2());

    private String getUpToken() {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//        return auth.uploadToken(BUCKETNAME, null, 3600, new StringMap().put("insertOnly", 1));
        return auth.uploadToken(BUCKETNAME);
    }

    /**
     *
     * @param inputStream 文件输入流
     * @param id 文件名
     * @return
     */
    public String putInputStream(InputStream inputStream,String id){
        //上传凭证
        UploadManager uploadManager = new UploadManager(cfg);
        String upToken = getUpToken();
        id = id.replace("-","" );
        try{
            Response response = uploadManager.put(inputStream,id , upToken, null,null );
            //解析
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            String key = putRet.key;
            String hash = putRet.hash;
            return DOMAIN + "/" + key;
        }catch (QiniuException e1){
            Response r = e1.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            }catch (QiniuException e2){
            }
        }
        return null;
    }

    /**
     * base64上传
     * @param imageContent
     * @return
     * @throws Exception
     */
    public String uploadFileAsImageString(String imageContent) throws Exception{
        byte[] fileBytes = getFileBytes(imageContent);
        String id = getKey();

        //上传凭证
        UploadManager uploadManager = new UploadManager(cfg);
        String upToken = getUpToken();
        id = id.replace("-","" );
        try{
            Response response = uploadManager.put(fileBytes,id,upToken);
            //解析
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            String key = putRet.key;
            String hash = putRet.hash;
            String iamgePath = DOMAIN + "/" + key;
            return iamgePath;
        }catch (QiniuException e1){
            Response r = e1.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            }catch (QiniuException e2){
            }
        }
        return null;
    }
    private byte[] getFileBytes(String imageContent) throws Exception{
        String prefix = getImageContentPrefix(imageContent);
        String fileSuffix = "";
        if(!StringUtils.isEmpty(prefix)){
            imageContent = imageContent.replaceAll(prefix,"");
            prefix = prefix.replaceAll("data:image/","");
            prefix = prefix.replaceAll(";base64,","");
            fileSuffix = prefix;
        }
        if(StringUtils.isEmpty(fileSuffix))
            fileSuffix = "jpeg";
        byte[] imageByteArray = new BASE64Decoder().decodeBuffer(imageContent);
        return  imageByteArray;
    }
    private String getImageContentPrefix(String imageContent) throws Exception{
        Pattern pattern = Pattern.compile("data:image/.*;base64,");
        Matcher matcher = pattern.matcher(imageContent);
        String prefix = "";
        while (matcher.find()) {
            prefix = matcher.group(0);
        }
        return prefix;
    }
    private String getKey(){
        String newFileName = UUID.randomUUID().toString() + ".jpg";
        return newFileName;
    }
    //base64方式上传
    public String put64image(byte[] base64, String key) throws Exception{
        String file64 = Base64.encodeToString(base64, 0);
        Integer l = base64.length;
        String url = "http://upload.qiniu.com/putb64/" + l + "/key/"+ UrlSafeBase64.encodeToString(key);
        //非华东空间需要根据注意事项 1 修改上传域名
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        //System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        System.out.println(response);
        //如果不需要添加图片样式，使用以下方式
        return DOMAIN + key;
//        return DOMAIN + key + "?" + style;
    }

    // 普通删除
    public void delete(String key) throws IOException {
        key = key.replace(DOMAIN + "/","");
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth,cfg );
        try{
            bucketManager.delete(BUCKETNAME, key);
        }catch (QiniuException e){
            System.err.println(e.code());
            System.err.println(e.response.toString());
        }
    }

    class Ret {
        public long fsize;
        public String key;
        public String hash;
        public int width;
        public int height;
    }

    private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException
    {
        File desc = new File(File.separator + filename);

        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists())
        {
            desc.createNewFile();
        }
        return desc;
    }

}
